package jvm.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * 引用队列  对象被释放后会放到引用队列里保存一下
 * @author jiangwz
 * @create 2019/9/17.
 */
public class ReferenceQueueDemo {

    public static void main(String[] args){

        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        // weakReference 弱引用
        WeakReference<Object> weakReference =new WeakReference<>(o1, referenceQueue);

        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());//weakReference 被gc清理后才会出现在应用队列里

        System.out.println("===========");

        o1 = null;
        System.gc();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
    }
}
